package caidan.net;
import jinyilw.common.file.Transfer;
import jinyilw.swing.visuals.PopWindow;
import jinyilw.swing.visuals.ProgressWindow;
import jinyilw.tools.net.UpdateTools;

import java.io.File;
public class UpdateTransfer extends ProgressWindow
		implements
		Transfer
{
	private static final long serialVersionUID = -269662719890483065L;
	private static FinishWindow finishPopWindow;

	public UpdateTransfer()
	{
		setInfoText("正在下载更新……");
	}

	@Override
	public void initStatus(String fileName, String fileSize, float percent)
	{
		setValue(0);
		showPopWindow();
	}

	@Override
	public void processStatus(float percent, String speed, String usedTime)
	{
		setValue((int) percent);
	}

	@Override
	public void endStatus(File file, long fileLen, long transLen)
	{
		dispose();
		if (fileLen != transLen)
		{
			file.delete();
			file = null;
		}
		getFinishPopWindow(file).showPopWindow();
	}

	public static FinishWindow getFinishPopWindow(File updateFile)
	{
		if (finishPopWindow == null)
			finishPopWindow = new FinishWindow();
		finishPopWindow.setUpdateFile(updateFile);
		return finishPopWindow;
	}

	static class FinishWindow extends PopWindow
	{
		private static final long serialVersionUID = -732999244294089489L;
		private File updateFile;
		public FinishWindow()
		{
			setClickDispose(false);
			addChooseOperater((Object o) ->
			{
				dispose();
				if (updateFile != null)
				{
					UpdateTools.restartAppToUpdate();
				}
			});
		}
		public void setUpdateFile(File file)
		{
			if (file != null && file.isFile())
			{
				updateFile = file;
				setInfoText("可用更新下载完成!");
				setChooseText("重启软件");
			} else
			{
				updateFile = null;
				setInfoText("下载异常！请重新更新");
				setChooseText("关闭");
			}
		}
	}
}